import requests,socket,json,time,random,hashlib,datetime;
import mysql.connector;

# import pandas as pd,numpy;



class guiJi:

	def v_code(self): #生成随机数
	    ret = ""
	    for i in range(6):
	        num = random.randint(0, 9)
	        # num = chr(random.randint(48,57))#ASCII表示数字
	        letter = chr(random.randint(97, 122))#取小写字母
	        Letter = chr(random.randint(65, 90))#取大写字母
	        s = str(random.choice([num,letter,Letter]))
	        ret += s
	    return ret

	def getStonk(self):  #获取stoke

		accessKey='MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCLZzlW68fR5x7vztskx9IvUNpsZpqfzK1QZTmQb-XH3Nn3LOGBlCMCJ_G3OQczfJnQumsqrz_vRI8c9gWhACLIwUHcHEntD3YekwxxdCR0S2EPZlwjk2t9DYHYUZQvBGHt0luclKGsP85hLCWgNMeJVKPCUPfZNwHTxBoThBwfIQIDAQAB'

		nonce=self.v_code()

		t=time.time()

		timestamp=int(round(t * 1000))

		secretKey='MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAItnOVbrx9HnHu_O2yTH0i9Q2mxmmp_MrVBlOZBv5cfc2fcs4YGUIwIn8bc5BzN8mdC6ayqvP-9Ejxz2BaEAIsjBQdwcSe0Pdh6TDHF0JHRLYQ9mXCOTa30NgdhRlC8EYe3SW5yUoaw_zmEsJaA0x4lUo8JQ99k3AdPEGhOEHB8hAgMBAAECgYEAidXmvCslyEXeMP83b4akLGSlk8lf2eFm_LcZ09bQPG4CloOp9ZWjh943AhNBK4doDxpEHFBrxwji-J_JsQeRW7TUZXEBZ3_JQJUO9pnB-kWNqBTcJYTrlCAwsLtJTo0KfAhj5lUupU_y-hmx6wB1mDsu-k2bsIkgSbBkzJxYxgECQQDb6RhW-Ag8ZUYFaVkNVX6Etm9nrH7k5wEURKXw1RENW15bbZnAEy2MbBTSVwvdO7b5kJhwyF7lRnVRCK7HRBqlAkEAokfY3I3YrvhRq4mDMRv_Ok8rbQiqPW5DCcfwVujL9Ods4J3t3zgsBxq0eHq-nrfYOzBIGoEm_VftvltcY7JVzQJAS2pNsY2P7X5hm_t70anPIJ4b6HbscX2TDitYqRW4qlb6LeqRPqCVD0IFhfjaFb2jy0Q-MvdUK9aU5vxOTAHcDQJAG0APVXHoSfFe3Xw48H0wDZ2PwD5tP-WNEk5luGJdJWHbMZizggFPu12ronOSINrkT4QbB4BaiL5EKOv0hrVCnQJAFkBEdSqxe11Jc-HTsEq77VzK7pz3PD6Q9xt2PsvQ5daVm3kfSdWzrfcUciqLyN9FvZPFojRX2FEOkAOLpZosyw'

		md5='accessKey='+accessKey+'&nonce='+nonce+'&timestamp='+str(timestamp)+secretKey

		m= hashlib.md5(md5.encode())

		url_params= {
		'timestamp':str(timestamp)
		,'accessKey':accessKey
		,'signType':'MD5'
		,'nonce':nonce
		,'sign':m.hexdigest()
		}

		return json.dumps(url_params)


	def getAi(self,url,obj):  #获取任务列表

		headers={'Content-type': 'application/json'}

		dcit=json.loads(self.getStonk())

		#print("字典值 : %s" % obj.items())

		#遍历字典列表添加obj到dcit
		for key,values in  obj.items():
			dcit[key]=values

		r=requests.post(
		 'https://bss.guiji.ai:18089'+url
		 ,data=json.dumps(dcit)
		 ,headers=headers)

		return r.text



	def setJson(self):

		endCallTime=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S');

		startCallTime=(datetime.datetime.now()-datetime.timedelta(hours=250)).strftime('%Y-%m-%d %H:%M:%S')

		mydict=self.getAi('/thirdApi/bss/queryPlanCallList',{'pageNo':'1','pageSize':'3000','startTime':startCallTime,'endTime':endCallTime,'statusList':[1,2]})
		
		renwuList=json.loads(mydict)['body']['list']

		arr=[]

		for renwu in renwuList:
			planId=renwu['id']
			planName=renwu['planName']

			mydict1=self.getAi('/thirdApi/bss/queryPlanPhonePage',{'planId':planId,'pageNo':"1",'pageSize':renwu['planNum'],'fStatusList':[0],'startCallDur':20,'endCallDur':500})
			tellList=json.loads(mydict1)['body']['list']

			for tellLi in tellList:

				tellLi['renWuName']=planName

			arr.extend(tellList)

			list_count=len(tellList)

			print('硅基任务名称：'+planName)
		# 	print(list_count)
		# 	#count_str=str(list_count)
		
		# 	#print('数量：'+str(len(tellList)))
		#tellList=json.dumps(arr)

		return arr

	#print((datetime.datetime.now()-datetime.timedelta(hours=12)).strftime('%Y-%m-%d %H:%M:%S'))
	def upDb(self):

		mydb = mysql.connector.connect(
		  host="localhost",       # 数据库主机地址
		  user="root",    # 数据库用户名
		  passwd="root",   # 数据库密码
		  database="weizandata"
		)

		mycursor = mydb.cursor()
		upCount=0
		for item in self.setJson():

			val=[]
			filed=[]
			for key in item:
				filed.append(key)
				val.append('\"'+str(item[''+key+''])+'\"')

			filedStr=','.join(filed)
			valStr=','.join(val)
			sql="INSERT IGNORE INTO gj_datapnone("+filedStr+")value("+valStr+");"
			#print(sql+'\n')
			mycursor.execute(sql)
			mydb.commit()
			upCount=upCount+int(mycursor.rowcount)
		return upCount
	def sleeptime(self,hour,min,sec):

		return hour*3600 + min*60 + sec;

# obj1=guiJi()

# print(obj1.upDb())



# second = sleeptime(0,1,0);
# while 1==1:
# 	time.sleep(second);
# 	print(setJson())
#这是隔10分钟执行一次

if __name__ == '__main__':

	obj1=guiJi()

	print(obj1.upDb())

	# second = obj1.sleeptime(0,0,10);
	# while 1==1:
	# 	time.sleep(second);
	# 	print(obj1.upDb())
	# 这是隔10分钟执行一次
